package com.fitns.user.aop;

import com.baomidou.mybatisplus.toolkit.CollectionUtils;

import com.fitns.user.constant.RedisKey;
import com.fitns.user.dto.user.UserVO;
import com.fitns.user.exception.CommMsgCode;
import com.fitns.user.exception.ServiceException;
import com.fitns.user.service.user.UserService;
import com.fitns.user.utils.ContextUtils;
import com.fitns.user.utils.RedisUtil;
import com.xiaoleilu.hutool.lang.Validator;
import com.xiaoleilu.hutool.util.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Set;

@Component
@Slf4j
public class LoginInterceptor extends HandlerInterceptorAdapter {

	@Autowired
	private RedisUtil redisUtil;

	@Autowired
	private UserService userService;

	private static final Boolean loginFilterEnable=false;
	private static final Boolean privilegeFilterEnable=false;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		if (!loginFilterEnable) {
			return true;
		}
		// 获取token
		String token = ContextUtils.getToken();
		// 根据请求生成URLcode
		String uri = request.getRequestURI();
		// String contextPath = request.getServletContext().getContextPath();
		// uri = uri.replaceAll(contextPath, "");
		String code = ContextUtils.generateUrlCode(uri, RequestMethod.valueOf(request.getMethod()));
		log.info("{token:" + token + ",code:" + code + "}");
		// 根据token获取UserId
		Long userId = userService.currentUser().getId();
		if (Validator.isNull(userId)) {
			throw ServiceException.create(CommMsgCode.UNAUTHORIZED);
		}

		// 根据UserId获取User roleId Set
		Set<Long> userRoleIds = userService.getUserRoleIds();
		if (CollectionUtils.isEmpty(userRoleIds)) {
			throw ServiceException.create(CommMsgCode.UNAUTHORIZED);
		}

		/*UserVO userVo = userService.currentUser();
		userService.updateExpiredTime(userVo);*/
		if (!privilegeFilterEnable) {
			return true;
		}
		// 根据请求生成URLcode
		// String contextPath = request.getServletContext().getContextPath();
		// uri = uri.replaceAll(contextPath, "");
		log.info("{token:" + token + ",userId:" + userId + ",code:" + code + "}");

		// 根据URL code获取可访问的角色ID列表
		@SuppressWarnings("unchecked")
        Set<Long> codeRoleIds = redisUtil.get(RedisKey.URL_CODE_MAP_ROLE_IDS.of(code), Set.class);
		// 判断用户是否有权限访问
		boolean isAuth = CollectionUtil.containsAny(codeRoleIds, userRoleIds);

		if (isAuth) {
			return true;
		} else {
			throw ServiceException.create(CommMsgCode.UNAUTHORIZED);
		}
	}

}
